import kk from 'kokos'
import { eventType } from '../utils/constantEnum'

const isSwallow = false

cc.Class({
    extends: cc.Component,

    onLoad() {
        // 设置成常驻节点
        cc.game.addPersistRootNode(this.node)

        this.node.zIndex = 9999
        this.lastEffect = null
        this.mask = this.node.getChildByName('changeSceneMask')

        this.node.on(cc.Node.EventType.TOUCH_START, this.handleTouchStart, this)

        kk.event.on(eventType.hideTouchEffect, this.hideLastTouchEffect, this)
        kk.event.on(eventType.showChangeScene, this.showChangeSceneMask, this)
    },

    onDestroy() {
        kk.event.off(eventType.hideTouchEffect, this.hideLastTouchEffect, this)
        kk.event.off(eventType.showChangeScene, this.showChangeSceneMask, this)
    },

    start() {
        if (this.node._touchListener) {
            // console.log('事件吞噬')
            this.node._touchListener.setSwallowTouches(isSwallow)
        }
    },

    hideLastTouchEffect() {
        try {
            this.lastEffect.active = false
        } catch (e) {

        }
    },

    handleTouchStart(e) {
        const position = e.getLocation()

        kk.event.emit(eventType.hidePropDesc)
        this.generateEffect(position)
        this.hideLastTouchEffect()
    },

    generateEffect(worldPosition) {
        const url = 'prefab/utils/touchParticle'
        cc.loader.loadRes(url, cc.Prefab, (err, prefab) => {
            const p = cc.instantiate(prefab)
            const nodePosition = this.node.convertToNodeSpaceAR(worldPosition)
            p.parent = this.node
            p.setPosition(nodePosition)
            this.lastEffect = p
        })
    },

    showChangeSceneMask() {
        this.mask.showSlowly()
        this.scheduleOnce(() => {
            this.mask.hideSlowly()
        }, 1)
    },

    // update(dt) {},
});
